<template>
  <el-dialog :title="title" center :visible.sync="show" width="400px" :append-to-body="true" custom-class="login" :close-on-click-modal="false" :show-close="true">
    <el-row>
      <el-form :model="loginForm" status-icon ref="loginForm" class="login-form" v-show="!third_show">
        <h2>
          <span> 没有帐号? <el-button size="mini" type="text" @click="wx_login">微信扫码登录</el-button>
          </span>
        </h2>
        <br />
        <el-form-item prop="phoneno"
          :rules="[{required: true, message: '请输入手机号码',trigger: 'blur'},{pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,message: '请输入正确的手机号码'}]">
          <el-input prefix-icon="el-icon-user" v-model="loginForm.phoneno" autocomplete="off" placeholder="请输入手机号">
          </el-input>
        </el-form-item>
        <el-form-item prop="pwd" :rules="[{required: true, message: '请输入密码',trigger: 'blur'}]">
          <el-input prefix-icon="el-icon-unlock" type="password" v-model="loginForm.pwd" autocomplete="off"
            :placeholder="pwdtext"></el-input>
        </el-form-item>
        <template v-if="!bind_moblie_show">
          <div class="input-field" v-if="loginfailcount>3">
            <span class="icon iconfont icon-yanzhengma2"></span>
            <el-form-item prop="pwd" :rules="[{required: true, message: '请输入验证码',trigger: 'blur'}]">
              <el-input type="text" name="txt_code" placeholder="验证码" v-model="loginForm.code" maxlength="4"></el-input>
            </el-form-item>
            <img class="captchaimg" onclick="javascript:Login.reloadCaptchaImage()" :src="codeimg" />
          </div>
          <el-form-item v-if="!bind_moblie_show">
            <el-button type="primary" @click="login('loginForm')" long size="large" :disabled="disabled"
              :loading="btnloading" style="width:100%;">登录</el-button>
          </el-form-item>
        </template>
        <template v-else>
          <!--绑定手机验证码-->
          <el-form-item>
            <el-input prefix="md-barcode" placeholder="验证码" v-model="loginForm.mobile_vcode" maxlength="6"></el-input>
            <el-button type="default" @click="send_code()">{{send_btn_text}}</el-button>
          </el-form-item>
          <div class="btn-bar">
            <el-button type="primary" :loading="btnloading" :disabled="disabled" @click="bind()">确定</el-button>
          </div>
        </template>
      </el-form>
      <div v-show="third_show" class="third_plan" key="l2">
        <div id="third_login_div" style="text-align:center;">加载第三方登录..</div>
        <!-- <iframe style="width:100%;heigh:100%" src="http://localhost:8081/user/wxlogin?action=bind_mobile&wid=ouf7Wt5FluC6xbc9ScfJ3y4MHolc&uid=27&name=Rob&avatar=oz0a50dbMJOxzID1_z7cgppKuGac"></iframe> -->
        <div class="backarrow" @click="ac_login">
          <i class="el-icon-arrow-left"></i>返回 </div>
      </div>
      <div class="third-bar" v-if="bind_moblie_show">
        <a class="skip-text" @click="skip_text()">下次再说</a>
      </div>
    </el-row>
  </el-dialog>
</template>

<script>
  import { mapState, mapMutations } from "vuex";
  export default {
    name: "Login",
    data() {
      return {
        loginForm: {
          phoneno: "",
          pwd: "",
          code: "",
          mobile_vcode: ""
        },
        show: false,
        loginfailcount: 0, //document.getElementById('csrf_state').value,
        tiptext_css: "",
        codeimg: "/base/getcaptcha",
        third_show: false,
        bind_moblie_show: false,
        thrid_div: null,
        showtext: "",
        btn_class: "btn-primary",
        disabled: false,
        btnloading: false,
        callback: null,
        api_callback: null,
        countdown: 60,
        title: "手机号登录",
        send_btn_text: "点我发送",
        pwdtext: "登录密码",
        wid: null,
        uid: null,
        username: "",
        code_timeout: -1,
        user: null
      };
    },

    computed: {
      ...mapState("user", {
        isLogin: state => state.isLogin,
        //showLoginModal: state => state.showLoginModal
      })
    },
    methods: {
      // ...mapMutations([
      //   //去vuex的actions中取出名为\\\的函数放到此地
      //   'setUser', 'SET_isLogin'
      // ]),

      load_script: function (src, callback) {
        var script = document.createElement("script"),
          loaded;
        script.setAttribute("src", src);
        if (callback) {
          script.onreadystatechange = script.onload = function () {
            if (!loaded) {
              callback();
            }
            loaded = true;
          };
        }
        document.getElementsByTagName("head")[0].appendChild(script);
      },
      login(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            var user = this.loginForm.phoneno,
              psw = this.loginForm.pwd,
              captcha = this.loginForm.code;
            this.btnloading = "loading";
            this.$axios.post("/api/user/login", {
                username: user,
                password: psw,
                captcha: captcha,
                remember_me: true
              })
              .then(res => {
                if (res.status == 200) {
                  let data = res.data;
                  if (data.code == 200) {
                    data.login = true;
                    this.reset();
                    this.$emit("update", data);
                  } else {
                    if (data.code == 601) {
                      this.showtext = "验证码错误";
                    }
                    // else if( data.message == "noverify" ){
                    //     location.href='/Signup?setp=2&setpcode='+data.setpcode +'&mail='+data.mail;
                    // }
                    else {
                      this.$message.error("登录失败，用户名或密码错误");
                      this.loginfailcount = data.logincount;
                    }
                  }
                } else {
                  this.$message.error("请求失败" + str(res.status));
                }
                this.btnloading = false;
              })
              .catch(error => {
                this.$message.error("服务暂时不可用，请过段时间再试");
                this.btnloading = false;
              });
          } else {
            return false;
          }
        });
      },
      wx_login() {
        this.title = ''
        this.third_show = true;
        this.load_script("http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js", () => {
            new WxLogin({
              self_redirect: true,
              id: "third_login_div",
              appid: "wx48a3208e6327fb2b",
              scope: "snsapi_login",
              redirect_uri: encodeURI("http://tuyibo.cn/api/user/wxlogin?ref=third_wx&state=" + Math.random() ),
              state: ""
            });
            this.thrid_div = document.getElementById("third_login_div");
          }
        );
      },
      ac_login() {
        this.third_show = false;
      },
      show_bind_moblie: function (data) {
        this.wid = data.wid;
        this.uid = data.userid;
        this.username = data.name;
        this.third_show = false;
        this.bind_moblie_show = true;
        this.title = "绑定手机";
        this.loginForm.pwd = "";
        this.pwdtext = "设置登录密码";
      },
      __set_time: function () {
        if (this.countdown == 0) {
          this.send_btn_text = "点我发送";
          this.countdown = 60;
          clearTimeout(this.code_timeout);
          this.code_timeout = -1;
          return;
        } else {
          this.send_btn_text = "已发送(" + this.countdown + ")";
          this.countdown--;
        }

        this.code_timeout = setTimeout(() => {
          this.__set_time();
        }, 1000);
      },
      send_code() {
        if (this.code_timeout != -1) return;
        var num = this.loginForm.phoneno;
        if (this.check_moblie_num(num) == false) return;

        this.__set_time();
        this.$axios.post("api/base/sendcode", { tonum: num }).then(res => {
            let b = res.data;
            if (b.code == 200) {
              this.$message.success("验证码已发送，请留意您的手机");
            } else {
              if (b.msg == "nov") {
                this.$message.error("验证码不符");
              } else if (b.msg == "max") {
                this.$message.error("发送验证码次数超出，请过段时间再试");
              } else if (b.msg == "sd") {
                this.$message.success("验证码已发送，请留意您的手机");
              } else {
                this.$message.error("参数错误");
              }
            }
          })
          .catch(error => {
            this.$message.error("服务暂时不可用，请过段时间再试");
          });
      },
      check_moblie_num(num) {
        if (num == "") {
          alert("请输入手机号");
          return false;
        }

        if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(num)) {
          this.$message.error("不是完整的11位手机号或者正确的手机号前七位");
          return false;
        }

        return true;
      },
      bind: function () {
        var user = this.loginForm.phoneno,
          psw = this.loginForm.pwd,
          captcha = this.loginForm.mobile_vcode;

        if (user == "") {
          this.$message.error("请输入手机号");
          return false;
        }

        if (psw == "") {
          this.$message.error("请输入密码");
          return false;
        }
        if (captcha == "") {
          this.$message.error("请输入验证码");
          return false;
        }

        var pdata = {
          mobile: user,
          checkcode: captcha,
          password: psw,
          wid: this.wid,
          uid: this.uid
        };
        this.btnloading = true;
        this.$axios.post("/api/user/bind_mobile", pdata).then(response => {
            let data = response.data;
            if (data.code == 200) {
              this.$message.success("绑定成功");
              this.btnloading = false;
              this.reset({ name: this.username, userid: this.uid });
            } else {
              this.btnloading = false;
              if (data.code == 404) {
                this.$message.error("找不到该用户");
                // this.showtext = '找不到该用户';
              } else if (data.code == 502) {
                this.$message.error("未登录");
                // this.showtext = '未登录';
              } else if (data.code == 504) {
                this.$message.error("验证码不符");
                // this.showtext = '验证码不符';
              } else if (data.code == 503) {
                this.$message.error("验证码已失效");
                // this.showtext = '验证码已失效';
              } else if (data.code == 505) {
                this.$message.error("手机号与接收的号码不符");
                // this.showtext = '手机号与接收的号码不符';
                this.send_btn_text = "点我发送";
                this.countdown = 60;
                clearTimeout(this.code_timeout);
                this.code_timeout = -1;
              } else if (data.code == 506) {
                this.$message.error("手机号已被绑定");
                // this.showtext = '手机号已被绑定';
              } else if (data.code == 600) {
                this.skip_text();
                //this.showtext = '您已经在兄弟站点 '+ data.name +' 绑定了手机号，可以直接进行登录'
                this.$message.success({
                  content:
                    "您已经在兄弟站点 " +
                    data.name +
                    " 绑定了手机号，可以直接使用该手机号进行登录",
                  duration: 10,
                  closable: true
                });
              } else if (data.code == 507) {
                this.$message.error("绑定手机号失败，请过段时间再试");
                // this.showtext = '绑定手机号失败，请过段时间再试';
                this.skip_text();
                throw "serer error!";
              } else {
                this.$message.error("未知错误");
                // this.showtext = '未知错误!';
              }
            }
          })
          .catch(error => {
            this.$message.error("服务暂时不可用，请过段时间再试");
            // this.showtext = '服务暂时不可用，请过段时间再试';
            this.btnloading = false;
          });
      },
      reset: function (s) {
        if (this.thrid_div != null) {
          this.thrid_div.firstElementChild.remove();
          this.thrid_div = null;
        }
        if (this.callback != null) {
          this.callback(s);
          this.callback = null;
        }
        if (this.api_callback != null) {
          this.api_callback();
          setTimeout(() => {
            this.api_callback = null;
          }, 20);
        }
        this.show = false;
      },
      skip_text: function () {
        this.reset({
          name: this.username,
          userid: this.uid
        });
      }
    }
  };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
  ::v-deep.login {
    .el-dialog__header {
      display: none;
    }

    .el-dialog__body {
      padding: 0;

      .slogan {
        width: 400px;
        height: 450px;
        padding: 50px;
        border-radius: 2px 0 0 2px;
        background: url("../../assets/images/login/img_login.jpg") center top / cover no-repeat;
        color: @white;

        h2 {
          font-size: 32px;
          line-height: 1.4;
          margin-bottom: 20px;
        }

        .special-p {
          margin: 30px 0 10px;
          opacity: 0.7;
        }
      }

      .login-form {
        padding: 50px;

        h2 {
          font-weight: 600;
          margin-bottom: 30px;
          line-height: 1;
          font-size: 24px;
          display: flex;
          align-items: flex-start;
          justify-content: space-between;

          >span {
            margin-left: auto;
            font-size: 12px;
            font-weight: lighter;
          }
        }
      }
    }
  }
</style>